package com.yehuishou.controller;

import java.io.UnsupportedEncodingException;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.alipay.api.domain.ItermInfo;
import com.github.pagehelper.PageInfo;
import com.yehuishou.dao.SaleOrderDao;
import com.yehuishou.dao.SellItemDao;
import com.yehuishou.pojo.Brand;
import com.yehuishou.pojo.Classify;
import com.yehuishou.pojo.Configurations;
import com.yehuishou.pojo.Item_order;
import com.yehuishou.pojo.Models;
import com.yehuishou.pojo.Oditem;
import com.yehuishou.pojo.Order;
import com.yehuishou.pojo.QueryVO;
import com.yehuishou.pojo.SellItemQueryParameters;
import com.yehuishou.pojo.ShoppingTrolley;
import com.yehuishou.pojo.User;
import com.yehuishou.service.SaleOrderService;

@Controller
public class SaleOrderController {

	@Autowired
	private SaleOrderService saleOrderService;
	@Autowired
	private SellItemDao sellitemdao;
	@Autowired
	private SaleOrderDao saleOrderDao;

	@RequestMapping("/content-3_2")
	public String SaleOrder(@RequestParam(required = true, defaultValue = "1") Integer pageNum,
			@RequestParam(required = true, defaultValue = "2") Integer pageSize, QueryVO vo, HttpServletRequest request,
			ModelMap mm) {
		vo.getOrder().setOrder_type(2);
		PageInfo<QueryVO> mv = saleOrderService.findUserOrder(pageNum, pageSize, vo);
		if (vo != null && vo.getOrder() != null) {
			SimpleDateFormat onetime = new SimpleDateFormat("yyyy-MM-dd");
			if (vo.getOrder().getStartdate() != null) {
				Date startDate = vo.getOrder().getStartdate();
				String format2 = onetime.format(startDate.getTime());
				request.setAttribute("onetime", format2);
			}
			if (vo.getOrder().getEnddate() != null) {
				Date startDate1 = vo.getOrder().getEnddate();
				String format = onetime.format(startDate1.getTime());
				request.setAttribute("endtime", format);
			}
		}
		// 将信息传到页面
		request.setAttribute("mv", mv);
		// 数据回显
		request.setAttribute("vo", vo);
		return "content-3_2";
	}

	@ResponseBody
	@RequestMapping("/deleteUser")
	public boolean deleteUser(QueryVO vo) {

		saleOrderService.deleteUser(vo);

		return true;
	}

	@RequestMapping("/details")
	public ModelAndView detailsById(String oid) {
		ModelAndView mv = new ModelAndView("content-3_2.1");
		List<Oditem> od = saleOrderService.finditems(oid);
		mv.addObject("mv", od);
		return mv;
	}

	// 删除订单明细
	@ResponseBody
	@RequestMapping("/detailsDelete")
	public Boolean UpdateItem(Integer i_id) {

		saleOrderService.detailsDelete(i_id);

		return true;
	}

	// 通过ID 查询 单个订单明细 返回到页面用于修改
	@RequestMapping("/FindDetailsById")
	public ModelAndView DetailsById(Oditem oditem) {
		ModelAndView mv = new ModelAndView();
		Oditem od = saleOrderService.FindDetailsById(oditem);
		List<Classify> classify = saleOrderService.selclassify();
		List<Brand> brand = saleOrderService.selbrand();
		List<Models> models = saleOrderService.selmodel();
		mv.addObject("od", od);
		mv.addObject("classify", classify);
		mv.addObject("brand", brand);
		mv.addObject("models", models);
		mv.setViewName("content-3_2.2");
		return mv;
	}

	// 更新订单明细
	@RequestMapping("/updateOitem")
	public String UpdateDetails(Oditem oditem) {
		Integer od = saleOrderService.UpdateDetails(oditem);
		Integer ct = saleOrderService.UpdateConfiguration(oditem);
		return "redirect:details?oid=" + oditem.getOid();
	}

	/**
	 * 
	 * @param i_id			订单中间表
	 * @param cfid			配置表
	 * @param mun			数量
	 * @return
	 */
	//添加购物车订单
	@ResponseBody
	@RequestMapping("/shoppingtrolley")
	public boolean addOrder (ShoppingTrolley shopt,HttpServletRequest request) {
		User user =(User) request.getSession().getAttribute("user");
		if(user!=null){		
			shopt.setUid(user.getUid());
			int i = saleOrderService.addOrderCat(shopt);
			if(i>0){
				return true;
			}else{
				return false;
			}			
		}
		return false;
	}
	
	
	//付款下单
	@RequestMapping("pay")
	public String pay(Integer[] stid,Integer[] i_id,Integer[] cfid,Integer[] mun,HttpServletRequest request){
		User user =(User) request.getSession().getAttribute("user");
		String a=(String) request.getSession().getAttribute("sellitemorder");
		if(a!=null){
			request.getSession().removeAttribute("sellitemorder");
			if(user!=null){
				//生成订单号oid
				String oid;
				SimpleDateFormat fmd = new SimpleDateFormat("yyyyMMddHHssmmSS");
				Thread tr =new Thread();
				synchronized (tr) {
					oid = fmd.format(new Date());
				}
				
				//总金额
				double payments=0;
				for (int i = 0; i < i_id.length; i++) {				
					SellItemQueryParameters siqp=new SellItemQueryParameters();
					siqp.setI_id(i_id[i]);
					siqp.setCfid(cfid[i]);
					List<Configurations> conf = sellitemdao.configurations(siqp);
					double payment=conf.get(0).getPrice()*mun[i];
					payments+=payment;

					Item_order item_order=new Item_order();
					item_order.setOid(oid);
					item_order.setI_id(i_id[i]);
					item_order.setCfid(cfid[i]);
					item_order.setMun(mun[i]);
					int w = saleOrderService.addOrderItem(item_order);	
				}
				Order order=new Order();
				order.setOid(oid);
				order.setUid(user.getUid());
				order.setPayment(payments);
				order.setStatus(1);
				order.setOrder_type(2);
				int q = saleOrderService.addOrder(order);
				
				//删除购物车数据
				if(stid!=null&&stid.length>0){
					for (int i = 0; i < stid.length; i++) {
						Integer stidd=stid[i];
						int w=saleOrderService.deleShoppingTrolley(stidd);
					}	
				}
					request.setAttribute("payments", payments);
					request.setAttribute("oid", oid);
					request.getSession().setAttribute("oid", oid);
					request.getSession().setAttribute("payments", payments);
					return "zupin06";
			}else{
				return "redirect:user";
			}
		}else{
			request.getSession().getAttribute("oid");
			request.getSession().getAttribute("payments");
			return "zupin06";
		}	
	}
	
	//选择支付类型
	@RequestMapping("moneyCheck")
	public String moneyCheck(String oid,Integer gender) throws UnsupportedEncodingException{
		List<Order> order=saleOrderService.selpayorder(oid);
		double payment=order.get(0).getPayment(); 
		
		if(gender==1){
			//微信支付
			//double转string
			Double d = new Double(payment*100);
	        NumberFormat nf = NumberFormat.getInstance();
	        nf.setGroupingUsed(false);
	        String payments = nf.format(d);
	        
			return "redirect:WxPay?oid=" + oid+"&payment="+payments;
		}
		if(gender==2){
			//支付宝支付
			//double转string
			Double d = new Double(payment);
	        NumberFormat nf = NumberFormat.getInstance();
	        nf.setGroupingUsed(false);
	        String payments = nf.format(d);
	        
			String WIDsubject=new String("耶回收官方商城".getBytes("UTF-8"),"ISO-8859-1");
			return "redirect:zfbfk?WIDout_trade_no=" + oid+"&WIDtotal_amount="+payments+"&WIDsubject="+WIDsubject;
		}
		return "redirect:index";
	}
	
	
	//个人主页订单
	@RequestMapping("order")
	public String order(@RequestParam(required = true, defaultValue = "1") Integer pageNum,
			@RequestParam(required = true, defaultValue = "5") Integer pageSize,@RequestParam(required = true, defaultValue = "1") Integer ul,HttpServletRequest request){
		User user=(User) request.getSession().getAttribute("user");
		if(user!=null){
			Integer uid=user.getUid();
			Map<String, Object> map=saleOrderService.selallorder(uid,ul,pageNum,pageSize);
			request.setAttribute("map", map);
			request.setAttribute("ul", ul);
			request.getSession().setAttribute("sellitemorder", "sellitemorder");
			return "order";
		}		
		return "redirect:user";
	}
	
	//未付款订单付款
	@RequestMapping("nonpayment_pay")
	public String nonpayment_pay(String oid,double payments,HttpServletRequest request){
		request.setAttribute("oid", oid);
		request.setAttribute("payments", payments);
		return "zupin06";
	}
	
	//删除出售订单
	@ResponseBody
	@RequestMapping("deleorder")
	public boolean deleorder(Item_order item_order){
		int i=saleOrderService.deleorder(item_order);
		int j=saleOrderService.deleitem_order(item_order);
		if(i>0){
			return true;
		}
		return false;
	}
	
	
	//删除回收订单
	@ResponseBody
	@RequestMapping("delebackorder")
	public boolean delebackorder(Item_order item_order){
		int i=saleOrderService.deleorder(item_order);
		int j=saleOrderService.delebackorder(item_order);
		if(i>0){
			return true;
		}
		return false;
	}
	
	//删除购物车订单
	@ResponseBody
	@RequestMapping("deleshopt")
	public boolean deleshopt(Integer stid){
		int i=saleOrderService.deleShoppingTrolley(stid);
		if(i>0){
			return true;
		}
		return false;
	}
		
		
		
	//用户确定回收金额
	@ResponseBody
	@RequestMapping("assess")
	public boolean assess(Order order){
		order.setStatus(4);
		int i=saleOrderService.assess(order);
		if(i>0){
			return true;
		}
		return false;
	}
	
	
	//查询购物车的数量
	@ResponseBody
	@RequestMapping("shopcar")
	public Integer shopcar(HttpServletRequest request){
		User user=(User) request.getSession().getAttribute("user");
		Integer uid=user.getUid();
		if(uid!=null){
			List<Order> shopt=saleOrderDao.selShoppingTrolley(uid);
			Integer count=shopt.size();
			return count;
		}
		//没登录
		return -1;
	}
	
	
	//查看物流信息跳转
	@RequestMapping("logistics")
	public String logistics(String logisticCode,HttpServletRequest request){
		System.out.println(logisticCode);
		request.setAttribute("LogisticCode", logisticCode);
		return "logistics";
	}
		
	
	//删除回收订单
	@ResponseBody
	@RequestMapping("deleleaseorder")
	public boolean deleleaseorder(Item_order item_order){
		int i=saleOrderService.deleorder(item_order);
		int j=saleOrderService.deleleaseorder(item_order);
		if(i>0){
			return true;
		}
		return false;
	}
	
	
	//删除回收订单
	@ResponseBody
	@RequestMapping("delebiddingorder")
	public boolean delebiddingorder(Item_order item_order,HttpServletRequest request){
		User user=(User) request.getSession().getAttribute("user");
		if(user!=null){
			item_order.setUid(user.getUid());
			int i=0;
			if(item_order.getOid()!=null&&item_order.getOid()!=""){
				i=saleOrderService.deleorder(item_order);
			}
			int j=saleOrderService.delebiddingorder(item_order);
			if(i>0||j>0){
				return true;
			}
			return false;
		}		
		return false;
	}
	
	
	//删除企业回收订单
	@ResponseBody
	@RequestMapping("deleenterpriseBacks")
	public boolean deleenterpriseBacks(Integer id,HttpServletRequest request){
		User user=(User) request.getSession().getAttribute("user");
		if(user!=null){
			int i=saleOrderService.deleenterpriseBacks(id);
			if(i>0){
				return true;
			}
			return false;
		}		
		return false;
	}
	
	
	//付款前库存检查
	@ResponseBody
	@RequestMapping("stocknumcheck")
	public boolean stocknumcheck(String oid){
		List<Item_order> item_orders=saleOrderDao.selitem_order(oid);
		if(item_orders.size()>0){
			for (int i = 0; i < item_orders.size(); i++) {
				SellItemQueryParameters siqp=new SellItemQueryParameters();
				siqp.setCfid(item_orders.get(i).getCfid());
				List<Configurations> conf = sellitemdao.configurations(siqp);
				if(item_orders.get(i).getMun()>conf.get(0).getStocknum()){
					return false;
				}
			}
		}
		return true;
	}
	
	
	
	/*//支付完成出售商品库存减少
	@RequestMapping("")
	public String stocknumdown(Order order){
		saleOrderService.stocknumdown(order);
		return "";
	}*/
	
	//添加快递跳转
	@RequestMapping("zlkedit")
	public String zlkedit(String oid , Model model) {
		model.addAttribute("oid", oid);
		return "zlkedit";
	}
	
	//添加快递
	@ResponseBody
	@RequestMapping("zlkeditadd")
	public Boolean zlkeditadd(Order ord) {
		saleOrderService.kdeit(ord);
		return true;
	}
	
	//end回调查快递单号
	@ResponseBody
	@RequestMapping("sellogisticCode")
	public String sellogisticCode(String oid) {
		Order ord = saleOrderService.findByO(oid);
		return ord.getLogisticCode();
	}

}
